import 'package:f_enjoy_plus/utils/RouteObserver.dart';
import 'package:f_enjoy_plus/utils/http.dart';
import 'package:f_enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';

class HomeList extends StatefulWidget {
  const HomeList({super.key});

  @override
  State<HomeList> createState() => _HomeListState();
}

class _HomeListState extends State<HomeList> with RouteAware {
  List notifyList = [];

  @override
  void initState() {
    super.initState();
    _getCommunityNotice();
    // _getMyRoomList();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 注册路由监听
    routeObserver.subscribe(this, ModalRoute.of(context)! as PageRoute);
  }

  /// 获取社区公告
  Future<void> _getCommunityNotice() async {
    try {
      final res = await http.get('/announcement');
      setState(() {
        notifyList = res;
      });
    } catch (error) {
      ToastUtils.error('获取失败: $error');
    }
  }

  /// 获取我的房屋列表
  _getMyRoomList() async {
    try {
      final res = await http.get('/room');
      print(res);
    } catch (error) {
      ToastUtils.error('获取失败: $error');
    }
  }

   @override
  void dispose() {
    routeObserver.unsubscribe(this); // 取消订阅
    super.dispose();
  }

  // 当页面完全显示时调用（首次进入或从其他页面返回）
  @override
  void didPushNext() {
    print("页面变为可见（进入前台）");
    // 这里相当于 pageShow 逻辑
  }

  // 当页面被覆盖时调用（跳转到新页面）
  @override
  void didPush() {
    print("页面首次加载");
  }

  // 当页面被覆盖时调用（跳转到新页面）
  @override
  void didPopNext() {
    print("页面从其他页面返回后重新显示");
    // 这里也是 pageShow 逻辑
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Image.asset('assets/images/notice@2x.png', width: 24),
            SizedBox(width: 8),
            Text(
              '社区',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            Text(
              '公告',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colors.orange,
              ),
            ),
          ],
        ),
        ListView(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.only(top: 12, bottom: 12),
          children:
              notifyList.map((item) {
                return GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(
                      context,
                      '/noticeDetail',
                      arguments: {'id': item['id']},
                    );
                  },
                  child: Container(
                    padding: EdgeInsets.all(12),
                    margin: EdgeInsets.only(bottom: 12),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      spacing: 8,
                      children: [
                        Text(
                          item['title'],
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          item['content'],
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        Text(
                          item['createdAt'],
                          style: TextStyle(fontSize: 12, color: Colors.grey),
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
        ),
      ],
    );
  }
}
